#include<disp_manager.h>

static PDispOpr g_ptDevicehead = NULL;
static PDispOpr g_ptDispDefault = NULL;
static DispBuffer g_tDispBuffer;


void RegisterDisplay(PDispOpr ptDispOpr)
{
   ptDispOpr->ptNext = g_ptDevicehead;
   g_ptDevicehead = ptDispOpr;
}

void DisplaySystemRegister(void)
{
	extern void FrameBufferRegister(void);
	FrameBufferRegister();
	//extern void WebRegister(void);
	//WebRegister();etc
}

int SelectDefaultDisplay(char* name)
{
	PDispOpr pTemp = g_ptDevicehead;
	while(pTemp)
	{
		if(strcmp(name,pTemp->name) == 0)
		{
			g_ptDispDefault = pTemp;
			return 0;
		}
		pTemp = pTemp->ptNext;
	}
	return -1;
}

int InitDefaultDisplay(void)
{
	int ret;
	
	ret = g_ptDispDefault->DeviceInit();
	if(ret)
	{
		printf("DeviceInit err\n");
		return -1;
	}

	ret = g_ptDispDefault->GetBuffer(&g_tDispBuffer);
	if(ret)
	{
		printf("ptDispBuffer err\n");
		return -1;
	}
	return 0;
}

int PutPixel(int x, int y, unsigned int color)
{
	unsigned int line_width = g_tDispBuffer.iXres * g_tDispBuffer.iBpp / 8;
	unsigned int pixel_width = g_tDispBuffer.iBpp / 8;
	
	unsigned char *pen_8 = (unsigned char *)g_tDispBuffer.buffer + y*line_width + x*pixel_width;
	unsigned short *pen_16;	
	unsigned int *pen_32;	

	unsigned int red, green, blue;	

	pen_16 = (unsigned short *)pen_8;
	pen_32 = (unsigned int *)pen_8;

	switch (g_tDispBuffer.iBpp)
	{
		case 8:
		{
			*pen_8 = color;
			break;
		}
		case 16:
		{
			/* 565 */
			red   = (color >> 16) & 0xff;
			green = (color >> 8) & 0xff;
			blue  = (color >> 0) & 0xff;
			color = ((red >> 3) << 11) | ((green >> 2) << 5) | (blue >> 3);
			*pen_16 = color;
			break;
		}
		case 32:
		{
			*pen_32 = color;
			break;
		}
		default:
		{
			printf("can't surport %dbpp\n", g_tDispBuffer.iBpp);
			break;
		}
	}
	
	return 0;
}

PDispBuffer GetDisplayBuffer(void)
{
   return &g_tDispBuffer;
}

int FlushDisplayRegion(PRegion ptRegion, PDispBuffer ptDispBuffer)
{
	return g_ptDispDefault->FlushRegion(ptRegion,ptDispBuffer);
}



